import React, {useRef} from "react";
import {createStyles} from "antd-style";
import useBackgroundImageStore from "@/components/Background/BackgroundImageStore.ts";

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            position: fixed;
            left: 0;
            top: 0;
            width: 100vw;
            height: 100vh;
            pointer-events: none;
            background-color: ${token.colorBgContainer};
            z-index: -1;

            img {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                transition: all 1s;
                transform: scale(1.5);
                z-index: 1;
                object-fit: cover;
                object-position: center;
            }
            
            .bg-loaded {
                opacity: 1;
                transform: scale(1);
            }

            canvas {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                z-index: 2;
            }
        `,
    }
})

const Background: React.FC = () => {
    const containerRef = useRef<HTMLDivElement>(null)
    const styles = useStyles().styles
    const backgroundImageSrc = useBackgroundImageStore(state => state.src)

    return (
        <div className={styles.container}
             ref={containerRef}
        >
            <img
                onLoad={(evt) => {
                    if (evt.target instanceof HTMLImageElement) {
                        const img = evt.target
                        img.classList.add('bg-loaded')
                    }
                }}
                onError={() => {
                    window.messageApi.error("背景图加载失败，请检查设置").then()
                }}
                src={backgroundImageSrc}
                alt="背景图"
            />
        </div>
    )
}

export default Background
